package com.allen.admin.service.server.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.allen.admin.service.common.domain.AdminPerm;
import com.allen.admin.service.common.service.AdminPermService;
import com.allen.admin.service.server.manager.impl.AdminPermManager;
import com.xxx.config.ModelResult;
import com.xxx.page.DataPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

@Service("adminPermService")
public class AdminPermServiceImpl implements AdminPermService {
	
	private final static Logger logger = LoggerFactory.getLogger(AdminPermServiceImpl.class);

	@Autowired
	private AdminPermManager adminPermManager;
	
	@Override
	public ModelResult<AdminPerm> create(AdminPerm obj) {
		ModelResult<AdminPerm> resultModelResult = new ModelResult<>();
		AdminPerm permission = adminPermManager.insert(obj);
		resultModelResult.withModel(permission);
		return resultModelResult;
	}

	@Override
	public ModelResult<AdminPerm> update(AdminPerm obj) {
		ModelResult<AdminPerm> resultModelResult = new ModelResult<>();
		AdminPerm permission = adminPermManager.update(obj);
		resultModelResult.withModel(permission);
		return resultModelResult;
	}

	@Override
	public ModelResult<AdminPerm> query(Long id) {
		ModelResult<AdminPerm> resultModelResult = new ModelResult<>();
		AdminPerm permission = adminPermManager.select(id);
		resultModelResult.withModel(permission);
		return resultModelResult;
	}

	@Override
	public ModelResult<List<AdminPerm>> query(AdminPerm qObj) {
		ModelResult<List<AdminPerm>> resultModelResult = new ModelResult<>();
		List<AdminPerm> list = adminPermManager.select(qObj);
		resultModelResult.withModel(list);
		return resultModelResult;
	}
	
	@Override
	public ModelResult<DataPage<AdminPerm>> queryPage(DataPage<AdminPerm> dataPage, AdminPerm qObj) {
		ModelResult<DataPage<AdminPerm>> resultModelResult = new ModelResult<>();
		dataPage = adminPermManager.queryPage(dataPage, qObj);
		resultModelResult.withModel(dataPage);
		return resultModelResult;
	}
	
	@Override
	public ModelResult<List<JSONObject>> queryBranchesAndLeafes() {
		ModelResult<List<JSONObject>>  resultModelResult = new ModelResult<>();

		List<JSONObject> list = new ArrayList<>();
		AdminPerm qObj = new AdminPerm();
		qObj.setParent(0L);
		qObj.setType(AdminPerm.TYPE_BRANCH);
		List<AdminPerm> branches = adminPermManager.select(qObj);
		
		qObj.setType(AdminPerm.TYPE_LEAF);
		for (AdminPerm branch : branches) {
			qObj.setParent(branch.getId());
			List<AdminPerm> leafes = adminPermManager.select(qObj);
			
			JSONObject jo = new JSONObject();
			jo.put("branch", branch);
			jo.put("leafes", leafes);
			
			list.add(jo);
		}

		resultModelResult.withModel(list);
		return resultModelResult;
	}
	
}
